/*   Copyright (C) 2021-2025 sirpdboy herboy2008@gmail.com https://github.com/sirpdboy/luci-app-ddns-go */

'use strict';
'require view';
'require fs';
'require ui';
'require uci';
'require form';
'require poll';

return view.extend({
    load: function() {
        return uci.load('ddns-go');
    },

    checkRunning: function() {
        return fs.exec('/bin/pidof', ['ddns-go']).then(function(pidRes) {
            if (pidRes.code === 0) return { isRunning: true };
            return fs.exec('/bin/ash', ['-c', 'ps | grep -q "[d]dns-go"']).then(function(grepRes) {
                return { isRunning: grepRes.code === 0 };
            });
        });
    },

    render: function() {
        var self = this;
        
        return this.checkRunning().then(function(checkResult) {
            var isRunning = checkResult.isRunning;
            var port = uci.get('ddns-go', 'config', 'port') || '[::]:9876';
            var noweb = uci.get('ddns-go', 'config', 'noweb') ;
            port = port.split(':').pop();
            
            var container = E('div');
            console.log('Debug: isRunning=' + isRunning + ', noweb=' + noweb + ', port=' + port);
            if (!isRunning || noweb === '1') {
            if (!isRunning) {
                var message = _('DDNS-GO Service Not Running');
            } 
	    if (noweb === '1') {
                var message = _('DDNS-GO Web Interface Disabled');
            }

                container.appendChild(E('div', { 
                    style: 'text-align: center; padding: 2em;' 
                }, [
                    E('img', {
                        src: '',
                        style: 'width: 100px; height: 100px; margin-bottom: 1em;'
                    }),
                    E('h2', {}, message)
                ]));
            } else {
                var iframe = E('iframe', {
                    src: window.location.protocol + '//' + window.location.hostname + ':' + port,
                    style: 'width: 100%; min-height: 100vh; border: none;'
                });
                container.appendChild(iframe);
            }
            
            poll.add(function() {
                return self.checkRunning().then(function(checkResult) {
                    var newStatus = checkResult.isRunning;
                    if (newStatus !== isRunning) {
                        window.location.reload();
                    }
                });
            }, 5);
            
            poll.start();
            
            return container;
        });
    },

    handleSaveApply: null,
    handleSave: null,
    handleReset: null
});